package cn.edu.zjgsu.controller;

import cn.edu.zjgsu.model.Author;
import cn.edu.zjgsu.service.AuthorService;
import cn.edu.zjgsu.templates.ResultBean;
import cn.edu.zjgsu.util.Constant;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by wqmei on 2017/10/2.
 */
@RestController
@EnableAutoConfiguration
public class LoginController
{
    @Autowired
    private AuthorService authorService;

    /**
     * 登录
     * @param author
     * @param request
     * @return
     */
    @PostMapping(path = "/author/login")
    public ResultBean<String> login(@RequestBody(required = false) Author author, HttpServletRequest request)
    {
        ResultBean<String> resultBean = new ResultBean<>();
        Boolean result = authorService.login(author);
        if (result)
        {
            HttpSession session = request.getSession();
            session.setAttribute(Constant.AUTHOR_ID, Long.valueOf(authorService.getAuthorId(author)));
            System.out.println("========  login success  =========");
            Subject subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(author.getLoginName(),author.getLoginPwd()));
            String roleName = authorService.getRoleByLoginName(author.getLoginName());
            resultBean.setData(roleName);
            return resultBean;
        }
        resultBean.wrongParameter();
        return resultBean;
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @PostMapping(path = "author/logout")
    ResultBean<Boolean> logout(HttpServletRequest request)
    {
        ResultBean resultBean = new ResultBean();
        resultBean.setData(Boolean.TRUE);
        HttpSession session = request.getSession();
        session.removeAttribute("adminId");
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return resultBean;
    }


}
